package zookeeper.leaderselector;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;
import zookeeper.utils.YamlUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author zhenzicheng
 * @DESCRIPTION: Leader选举demo
 * @DATE: 2022/04/25 11:22 AM
 */
public class LeaderSelectorDemo {
  private static final String CONNECT_STR;
  private static final RetryPolicy retryPolicy = new ExponentialBackoffRetry(5 * 1000, 10);
  private static final CountDownLatch countDownLatch = new CountDownLatch(1);
  private static CuratorFramework curatorFramework;

  static {
    CONNECT_STR = YamlUtil.getDefaultConnectStr();
  }

  public static void main(String[] args) throws InterruptedException {
    // 获取通过运行时给定的VM options参数
    String appName = System.getProperty("appName");

    curatorFramework = CuratorFrameworkFactory.newClient(CONNECT_STR, retryPolicy);
    curatorFramework.start();

    LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() {
      @Override
      public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
        System.out.println(" I'm leader now,my name is" + appName);
        TimeUnit.SECONDS.sleep(15);
      }
    };

    LeaderSelector selector = new LeaderSelector(curatorFramework, "/cachePreHeat_leader", listener);
    selector.autoRequeue();
    selector.start();
    countDownLatch.await();
  }
}

